//
//  ManageStaffVC.m
//  QRMaster
//
//  Created by myApple on 15/12/7.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "ManageStaffVC.h"
#import "MJRefresh.h"
#import "MJRefreshNormalHeader.h"
#import "PromptInfoView.h"
#import "StaffLogic.h"
#import "OpertionPlist.h"
#import "RequestNetWork.h"
#import "TouchBtnColor.h"
#import "checkPower.h"
#import "AppDelegate.h"
#import "CommunityManageTableViewCell.h"
#import "CommunityListInfo.h"
#import "ChineseString.h"
#import "pinyin.h"
#import "UIView+MaterialDesign.h"
#import "JudgeRole.h"
#import "QRSingleton.h"
#import "ChineseInclude.h"
#import "ZYPinYinSearch.h"
#import "GuestModel.h"
#import "deleteGuest.h"
#import "StaffManagerViewController.h"
#import "CommunityInfoLogic.h"
#import "BackTableViewCell.h"
#import "selectCommunityController.h"
#import "CommunityListModel.h"
#import "EditAfterAddViewController.h"
#import "AddMemberViewController.h"
#import "BackBtn.h"
#import "StaffAndClientFirstSectionCell.h"

#import "StaffLetterSort.h"

@interface ManageStaffVC ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchDisplayDelegate,UIGestureRecognizerDelegate>
{
    NSMutableArray * CommunityArray;//集群组
    NSMutableArray * staffInfoArray;//职员信息
    UIButton * addNmberBtn;
    NSIndexPath * indexPaths;
    UISearchBar * nameSearchBar;
    
    UISearchBar * staffSearchBar;
    UISearchDisplayController * guestDisplayController;
    NSMutableArray * sectionIndexArray;//section的标题
    NSMutableArray * rightIndexArray;//右边的字母索引
    UILabel * footLabel;//脚视图的lable
    NSMutableArray * searchSectionArray;
    NSMutableArray * searchRightArray;
    
    UILabel * communityLabel;
    UILabel * communityListLabel;
    
    NSString * communityID;//时刻记住物业ID；
    //    NSString * communityRole;//时刻记住物业权限;
    
    NSInteger managerRole;//显示当前人在当前集群的的角色
    
    NSMutableArray * sortArray;//排序后的数组
    
    BOOL havePower;//此人在当前物业中是否有权限
    
    
    NSMutableArray * deleteCellArray;//删除所选中的cell
    UIView * promtView;//没有职员时的提示
    
    QRSingleton * singleton;//单例 共享
    CommunityInfoLogic * timeStamp;//时间戳
    StaffLogic * staffDataBase;//职员的本地数据
    
    UIView * groupView;//当前角色是组管理员的时候显示
    UIButton * addStaffBtn;
    UIImageView * addStaffView;
    UILabel * addStaffLabel;
    //
    UILabel * promtTextLabel;
    UIButton * refreshBtn;
    UILabel * groupLabel;
    UILabel * titleLabel;
    BOOL netWorkStatus;
    
}

@end

@implementation ManageStaffVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"staff", @"成员");
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    sectionIndexArray = [[NSMutableArray alloc]init];
    rightIndexArray = [[NSMutableArray alloc]init];
    searchRightArray = [[NSMutableArray alloc]init];
    searchSectionArray = [[NSMutableArray alloc]init];
    singleton = [QRSingleton sharedQRSingleton];
    netWorkStatus = YES;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(netWorkBreakFromFile) name:@"netWorkBreak" object:nil];//断网从文件获取数据
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(JoinNetWorkRefresh) name:@"netWorkJion" object:nil];//连网就刷新一下数据
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeHeight:) name:@"height" object:nil];//改变tableview的高度
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeLanguage) name:@"changeLanguage"object:nil];
    [self prepareTabelView];
    [self GroupLoginView];
    self.view.backgroundColor = [UIColor whiteColor];
    CommunityArray = [[NSMutableArray alloc]init];
    staffInfoArray = [[NSMutableArray alloc]init];
    havePower = NO;
    sortArray = [[NSMutableArray alloc]init];
    deleteCellArray = [[NSMutableArray alloc]init];
    // Do any additional setup after loading the view.
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
        nameSearchBar.placeholder = NSLocalizedString(@"managerMentSearchContent", nil);
        [_CommunityTabelView reloadData];
       
        if (![communityID isEqualToString:singleton.communityId] || communityID == nil)
        {
            communityID = singleton.communityId;
            [self getDataFromDisk];
            [self lookCommunityRole];
        }
        else
        {
            [self getDataFromDisk];
        }
    self.navigationController.navigationBarHidden = NO;
}

#pragma mark -- 解决tableview中手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

#pragma mark -- 搜索代理方法

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES];
   
    for(id cc in [searchBar.subviews[0] subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:NSLocalizedString(@"alterCancel", nil) forState:UIControlStateNormal];
        }
    }
    
//    UIButton *btn=[searchBar valueForKey:@"_cancelButton"];
//    [btn setTitle:NSLocalizedString(@"alterCancel", nil)  forState:UIControlStateNormal];
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    for (UIView * subView in guestDisplayController.searchResultsTableView.subviews)
    {
        if ([subView isKindOfClass:[UILabel class]]) {
            UILabel * label = (UILabel *)subView;
            label.text = NSLocalizedString(@"noSearch", nil);
        }
    }
    return YES;
}


-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [searchSectionArray removeAllObjects];
    NSMutableArray * newArray = [[NSMutableArray alloc]init];
    newArray = [staffInfoArray mutableCopy];
    for (StaffModel * model in staffInfoArray)
    {
        if (([model.mobile rangeOfString:searchBar.text].location != NSNotFound && model.mobile != nil)||([model.email rangeOfString:searchBar.text].location != NSNotFound && model.email != nil))
        {
            [searchSectionArray addObject:model];
            [newArray removeObject:model];
        }
    }
    [searchSectionArray addObjectsFromArray:[NSMutableArray arrayWithArray:[ZYPinYinSearch searchWithOriginalArray:newArray andSearchText:searchBar.text andSearchByPropertyName:@"userName"]]];
    searchRightArray = [StaffLetterSort indexArray:searchSectionArray];
    searchSectionArray = [StaffLetterSort letterSortArray:searchSectionArray];
    
    [_CommunityTabelView reloadData];
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    
    sectionIndexArray = [StaffLetterSort letterSortArray:staffInfoArray];
    rightIndexArray = [StaffLetterSort indexArray:staffInfoArray];
    
    [_CommunityTabelView reloadData];
    
}

-(void)changeLanguage
{
    promtTextLabel.text = NSLocalizedString(@"noStaff", nil);
    [refreshBtn setTitle:NSLocalizedString(@"refreshStaff", nil) forState:0];
    groupLabel.text = NSLocalizedString(@"groupModel", nil);
}

//获取本地数据
-(void)getDataFromDisk
{
    staffDataBase = [[StaffLogic alloc]init];
    [staffInfoArray removeAllObjects];
    [staffDataBase queryStaffData:communityID block:^(NSMutableArray *staffArray)
    {
      if (staffArray.count > 0)
      {
          promtView.hidden = YES;
          _CommunityTabelView.hidden = NO;
          staffInfoArray = staffArray;
      }

        sortArray = [StaffLetterSort getChinesArray:staffInfoArray];
        
        sectionIndexArray = [StaffLetterSort letterSortArray:staffInfoArray];
        rightIndexArray = [StaffLetterSort indexArray:staffInfoArray];
        
        sortArray = sectionIndexArray;
        if (staffInfoArray.count == 0 || staffInfoArray.count == 1) {
            footLabel.text = [NSString stringWithFormat:@"%@ %lu %@",NSLocalizedString(@"total",nil),(unsigned long)staffInfoArray.count,NSLocalizedString(@"staff", nil)];
        }
        else
        {
            footLabel.text = [NSString stringWithFormat:@"%@ %lu %@",NSLocalizedString(@"total",nil),(unsigned long)staffInfoArray.count,NSLocalizedString(@"staffs", nil)];
        }
        
        [_CommunityTabelView reloadData];
    }];
    
}


-(void)lookCommunityRole
{
    if ([self IsHaveNetwork]) {
        [_CommunityTabelView.mj_header endRefreshing];
        return;
    }
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    __weak ManageStaffVC * weakSelf = self;
    power.powerBlock = ^(id data,id error)
    {
        if ([data objectForKey:@"data"] != nil) {
//            NSDictionary * communityDict = [data objectForKey:@"communities"];
            NSArray * CommunityData = [[data objectForKey:@"data"] objectForKey:@"communities"];
            if (communityID == nil) {
                communityID = [CommunityData[0] objectForKey:@"communityid"];
                [QRSingleton sharedQRSingleton].communityId = [CommunityData[0] objectForKey:@"communityid"];
                [QRSingleton sharedQRSingleton].communityName = [CommunityData[0] objectForKey:@"communityname"];
                communityLabel.text = [QRSingleton sharedQRSingleton].communityName;
            }
            else
            {
                for (NSDictionary * dict in CommunityData) {
                    if ([communityID isEqualToString:[dict objectForKey:@"communityid"]]) {
                        managerRole = [[dict objectForKey:@"role"]integerValue];
                        break;
                    }
                }
            }
            if (managerRole == 5) {
                groupView.hidden = NO;
            }
            else
            {
                groupView.hidden = YES;
                //不是组管理员就请求职员信息
                [weakSelf getData:communityID];
            }
            
        }
        else
        {
            if ([[error objectForKey:@"status"]integerValue] == 210) {
                sortArray = nil;
                [_CommunityTabelView reloadData];
                [staffDataBase deleteStaffByCommunityId:communityID];
            }
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        [_CommunityTabelView.mj_header endRefreshing];
    };
}

#pragma mark -- 当前角色是组管理员职员显示的情况
-(void)GroupLoginView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = self.view.frame.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight;
    
    groupView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    groupView.backgroundColor = RGBA(248, 248, 248, 1);
    groupView.hidden = YES;
    
    groupLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height / 2.0)];
    groupLabel.textAlignment = NSTextAlignmentCenter;
    groupLabel.text = NSLocalizedString(@"groupModel", nil);
    groupLabel.numberOfLines = 2;
    groupLabel.textColor = RGBA(211, 211, 211, 1);
    groupLabel.font = [UIFont systemFontOfSize:14.0];
    [groupView addSubview:groupLabel];
    [self.view addSubview:groupView];
}


#pragma mark -- 准备tableview
-(void)prepareTabelView
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = 44;
    
    //搜索条的
    staffSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(x, y, width, height)];
    staffSearchBar.placeholder = NSLocalizedString(@"accountOrName", nil);
    staffSearchBar.layer.masksToBounds = YES;
    staffSearchBar.keyboardType = UIKeyboardTypeNamePhonePad;
    staffSearchBar.delegate = self;
    [[[[staffSearchBar.subviews objectAtIndex:0]subviews]objectAtIndex:0]removeFromSuperview];
    staffSearchBar.backgroundColor = UIColorFromRGB(0xebebeb);
    guestDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:staffSearchBar contentsController:self];
    guestDisplayController.delegate = self;
    guestDisplayController.searchResultsDataSource = self;
    guestDisplayController.searchResultsDelegate = self;
    self.edgesForExtendedLayout = UIRectEdgeTop;
    self.extendedLayoutIncludesOpaqueBars = NO;
//    staffSearchBar.barTintColor = UIColorFromRGB(0xebebeb);
    //脚视图
    y = 0;
    height = 48;
    UIView * footView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    y = 15;
    height = 18;
    footLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    footLabel.textColor = UIColorFromRGB(0x333333);
    footLabel.font = [UIFont systemFontOfSize:12.0];
    footLabel.textAlignment = NSTextAlignmentCenter;
    [footView addSubview:footLabel];
    
    x = 0;
    y = 0;
    width = UI_SCREEN_WIDTH;
    height = UI_SCREEN_HEIGHT - 64;
    _CommunityTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStyleGrouped];
    _CommunityTabelView.delegate = self;
    _CommunityTabelView.dataSource = self;
    [self.view addSubview:_CommunityTabelView];
    _CommunityTabelView.tableFooterView = footView;
    _CommunityTabelView.backgroundColor = UIColorFromRGB(0xebebeb);
    __weak ManageStaffVC * weakSelf = self;
    _CommunityTabelView.sectionIndexBackgroundColor = [UIColor clearColor];
    [_CommunityTabelView.mj_header beginRefreshing];
    _CommunityTabelView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf lookCommunityRole];
    }];
    _CommunityTabelView.tableHeaderView = staffSearchBar;
    promtView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    promtView.backgroundColor = self.view.backgroundColor;
    promtView.hidden = YES;
    [self.view addSubview:promtView];
    
    promtTextLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, UI_SCREEN_HEIGHT / 2.0 , UI_SCREEN_WIDTH, 20)];
    promtTextLabel.text = NSLocalizedString(@"noStaff", nil);
    promtTextLabel.textColor =  RGBA(211, 211, 211, 1);
    promtTextLabel.textAlignment = NSTextAlignmentCenter;
    promtTextLabel.font = [UIFont systemFontOfSize:14.0];
    [promtView addSubview:promtTextLabel];
    
    x = 0;
    width = UI_SCREEN_WIDTH;
    height = 40;
    y = UI_SCREEN_HEIGHT / 2.0 - 50;
    refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    refreshBtn.frame = CGRectMake(x, y, width, height);
    [refreshBtn setTitle:NSLocalizedString(@"refreshStaff", nil) forState:0];
    [refreshBtn setTitleColor:RGBA(125, 194, 52, 1) forState:0];
    refreshBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [refreshBtn addTarget:self action:@selector(refreshStaff) forControlEvents:UIControlEventTouchUpInside];
    [promtView addSubview:refreshBtn];
}

#pragma mark -- 改变高度
-(void)changeHeight:(NSNotification *)not
{
    CGFloat height = [[not.userInfo objectForKey:@"height"]floatValue];
    _CommunityTabelView.frame = CGRectMake(0, 0, self.view.frame.size.width, UI_SCREEN_HEIGHT - height - 49 - 64);
}

#pragma mark  刷新tableview
-(void)refreshStaff
{
    [self getData:communityID];
}

#pragma mark === 断网和联网的数据以及显示处理
-(void)netWorkBreakFromFile
{
    netWorkStatus = NO;
    [staffInfoArray removeAllObjects];
    NSMutableDictionary * staffDict = [OpertionPlist readDataFromPlist];
    NSArray * array = [staffDict objectForKey:@"staffinfo"];
    [self analysisDataByModel:array];
    _CommunityTabelView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 40);
}

-(void)JoinNetWorkRefresh
{
    if (!netWorkStatus)
    {
        [self getCommunityData:nil];
    }
    
}

-(void)getCommunityData:(NSString *)comid
{
    [self lookCommunityRole];
}


-(void)getData:(NSString *)communtiyid
{
    if ([self IsHaveNetwork]) {
    [_CommunityTabelView.mj_header endRefreshing];
        return;
    }
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:communtiyid forKey:@"communityId"];
    [postDict setValue:@"1" forKey:@"withoutGroup"];
    
    if([self getTimestamp:communtiyid timeKey:@"member_timestamp"] != nil)
    {
        [postDict setValue:[self getTimestamp:communtiyid timeKey:@"member_timestamp"] forKey:@"timestamp"];
    }
    else
    {
        [postDict setValue:@"" forKey:@"timestamp"];
    }
    [self startWaiting:nil color:nil addToView:self.view];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [rnk initWithPath:POST(GETMEMBER) params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        NSDictionary * cache = [downLoadData objectForKey:@"cache"];
        if (cache!=nil) {
            [self updateTimestamp:communtiyid timeKey:@"member_timestamp" timeKeyValue:[cache objectForKey:@"timestamp"]];
            if([@"1" isEqualToString:[NSString stringWithFormat:@"%@",[cache objectForKey:@"status"]]]==YES)
            {
                 NSArray * data = [downLoadData objectForKey:@"data"];
                if(data != nil)
                {
                    //数据有更新，需先清除表中数据，再进行插入
                    promtView.hidden = YES;
                    _CommunityTabelView.hidden = NO;
                    NSArray * fileData = data;
                    staffDataBase = [[StaffLogic alloc]init];
                    [staffDataBase deleteStaffByCommunityId:communtiyid];
                    [[NSUserDefaults standardUserDefaults] setObject:communtiyid forKey:@"communityId"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    [self analysisDataByModel:fileData];
                }
            }
        }
        else if (error != nil) {
            if ([[error objectForKey:@"status"]integerValue]== 210) {
                staffDataBase = [[StaffLogic alloc]init];
                [staffDataBase deleteStaffByCommunityId:communtiyid];
                [PromptInfoView showMessage:[error objectForKey:@"info"]superView:self.view];
                promtView.hidden = YES;
                _CommunityTabelView.hidden = NO;
                [staffInfoArray removeAllObjects];
                [rightIndexArray removeAllObjects];
                [sectionIndexArray removeAllObjects];
                footLabel.text = [NSString stringWithFormat:@"%@ %lu %@",NSLocalizedString(@"total",nil),(unsigned long)staffInfoArray.count,NSLocalizedString(@"staff", nil)];
                [_CommunityTabelView reloadData];
            }
            else if([[error objectForKey:@"status"]integerValue] == 331)
            {
                [staffInfoArray removeAllObjects];
                promtView.hidden = NO;
                _CommunityTabelView.hidden = YES;
                [PromptInfoView showMessage:NSLocalizedString(@"notInCommunity", nil)];
                staffDataBase = [[StaffLogic alloc]init];
                [staffDataBase deleteStaffByCommunityId:communtiyid];
            }
            else
            {
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }
        }
        [_CommunityTabelView.mj_header endRefreshing];
        [_CommunityTabelView reloadData];
    }];
   
}

-(void)getBackData:(NSNotification *)not
{
    //每次返回列表刷新一次
    communityID = [not.userInfo objectForKey:@"communityid"];
    [self getData:communityID];
    promtTextLabel.text = NSLocalizedString(@"noStaff", nil);
    [refreshBtn setTitle:NSLocalizedString(@"refreshStaff", nil) forState:0];
}

-(void)AnalysisData:(NSNotification *)not
{
    NSArray * data = [not.userInfo objectForKey:@"data"];
    //存储数据到文件
    NSMutableDictionary * staffData = [OpertionPlist readDataFromPlist];
    [staffData setValue:data forKey:STAFFINFO];
    [OpertionPlist writeDataToPlist:staffData];
    [self analysisDataByModel:data];
}
-(void)analysisDataByModel:(NSArray * )data
{
    promtView.hidden = YES;
    if (data.count > 0) {
        [staffInfoArray removeAllObjects];
        [sortArray removeAllObjects];
        for (NSDictionary * dict in data) {
            StaffModel * model = [[StaffModel alloc]init];
            model.userID = [dict objectForKey:@"id"];
            model.headUrl = [dict objectForKey:@"headurl"];
            model.mobile = [dict objectForKey:@"mobile"];
            model.email = [dict objectForKey:@"email"];
            model.userName = [dict objectForKey:@"name"];
            model.sex = [dict objectForKey:@"gender"];
            model.StaffRole = [dict objectForKey:@"role"];
            model.areaCode = [dict objectForKey:@"areaCode"];
            [staffInfoArray addObject:model];
            staffDataBase = [[StaffLogic alloc]init];
            [staffDataBase insertStaffData:model withCommuntiyId:communityID];
        }
        sortArray = [StaffLetterSort getChinesArray:staffInfoArray];
        sectionIndexArray = [StaffLetterSort letterSortArray:staffInfoArray];
        
        sortArray = sectionIndexArray;
        rightIndexArray = [StaffLetterSort indexArray:staffInfoArray];
        if (staffInfoArray.count == 0 || staffInfoArray.count == 1) {
            footLabel.text = [NSString stringWithFormat:@"%@ %lu %@",NSLocalizedString(@"total",nil),(unsigned long)staffInfoArray.count,NSLocalizedString(@"staff", nil)];
        }
        else
        {
            footLabel.text = [NSString stringWithFormat:@"%@ %lu %@",NSLocalizedString(@"total",nil),(unsigned long)staffInfoArray.count,NSLocalizedString(@"staffs", nil)];
        }
    }
    [_CommunityTabelView reloadData];
    
}

#pragma mark ====判断是不是数字

-(BOOL)isNumber:(NSString *)string
{
    if ([string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]].length > 0) {
        return NO;
    }
    else
        return YES;
}

#pragma mark -- 通过传值来改变community来改变数据
-(void)GetStaffData:(NSNotification *)not
{
    communityID = [not.userInfo objectForKey:@"communityid"];
    [[NSUserDefaults standardUserDefaults] setObject:communityID forKey:@"communityId"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _CommunityTabelView) {
        return sectionIndexArray.count + 1;
    }
    return searchSectionArray.count;
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == _CommunityTabelView) {
         return rightIndexArray;
    }
    return searchRightArray;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == _CommunityTabelView) {
        if (section == 0) {
            return @"";
        }
        return rightIndexArray[section -1];
    }
    return searchRightArray[section];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _CommunityTabelView) {
        if (section == 0) {
            return 1;
        }
        NSArray * rowCount = sectionIndexArray[section - 1];
        return rowCount.count;
    }
    NSArray * rowCount = searchSectionArray[section];
    return rowCount.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _CommunityTabelView) {
        if (section == 0) {
            return 0.1;
        }
        return 34.0;
    }
    return 34.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _CommunityTabelView) {
        if (indexPath.section == 0) {
            NSString * identityId = @"cellId";
            StaffAndClientFirstSectionCell * cell = [tableView dequeueReusableCellWithIdentifier:identityId];
            if (!cell) {
                cell = [[StaffAndClientFirstSectionCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identityId];
            }
            cell.imageNameString = @"addStaff";
            cell.titleString = NSLocalizedString(@"addStaff", nil);
            return cell;
        }
        
        NSString * string = @"cell";
        CommunityManageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (!cell) {
            cell = [[CommunityManageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
            
        }
        
        NSArray * rowInfo = sectionIndexArray[indexPath.section -1];
        StaffModel * staffModel = [[StaffModel alloc]init];
        staffModel = rowInfo[indexPath.row];
        cell.userName = staffModel.userName;
        cell.headUrl = staffModel.headUrl;
        return cell;
    }
    else
    {
        NSString * string = @"cell";
        CommunityManageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (!cell) {
            cell = [[CommunityManageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
            
        }
        
        NSArray * rowInfo = searchSectionArray[indexPath.section];
        StaffModel * staffModel = [[StaffModel alloc]init];
        staffModel = rowInfo[indexPath.row];
        cell.userName = staffModel.userName;
        cell.headUrl = staffModel.headUrl;
        
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _CommunityTabelView) {
        if (indexPath.section == 0) {
            [self addMenber];
            return;
        }
        StaffManagerViewController * smvc = [[StaffManagerViewController alloc]init];
        NSArray * rowArray = sectionIndexArray[indexPath.section - 1];
        StaffModel * staffModel = rowArray[indexPath.row];
        smvc.communityId = communityID;
        smvc.role = managerRole;
        smvc.model = staffModel;
        smvc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:smvc animated:YES];
    }
    else
    {
        StaffManagerViewController * smvc = [[StaffManagerViewController alloc]init];
        NSArray * rowArray = searchSectionArray[indexPath.section];
        StaffModel * staffModel = rowArray[indexPath.row];
        smvc.communityId = communityID;
        smvc.role = managerRole;
        smvc.model = staffModel;
        smvc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:smvc animated:YES];
    }
    
}

#pragma mark -- 切换集群
-(void)changeCommunity
{
    selectCommunityController * scc = [[selectCommunityController alloc]init];
    scc.communityId = singleton.communityId;
    scc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:scc animated:YES];
    scc.communityBlock = ^(CommunityListModel * model)
    {
        managerRole = [model.role integerValue];
    };
}

#pragma mark --添加职员
-(void)addMenber
{
    //先请求一下当前集群的角色 防止同步操作
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    power.powerBlock = ^(id data,id error)
    {
        if ([data objectForKey:@"data"] != nil)
        {
            NSDictionary * communityDict = [data objectForKey:@"data"];
            NSArray * CommunityData = [communityDict objectForKey:@"communities"];
            for (NSDictionary * dict in CommunityData)
            {
                if ([communityID isEqualToString:[dict objectForKey:@"communityid"]])
                {
                    managerRole = [[dict objectForKey:@"role"]integerValue];
                    break;
                }
            }
            if (managerRole == 1 || managerRole == 2)
            {
//                EditAfterAddViewController * stvc = [[EditAfterAddViewController alloc]init];
//                stvc.communityID = communityID;
//                stvc.communityRole = [NSString stringWithFormat:@"%ld",(long)managerRole];
//                stvc.hidesBottomBarWhenPushed = YES;
//                [self.navigationController pushViewController:stvc animated:YES];
                
                AddMemberViewController * addMemberVC = [[AddMemberViewController alloc]init];
                addMemberVC.communityID = communityID;
                addMemberVC.communityRole = [NSString stringWithFormat:@"%ld",(long)managerRole];
                addMemberVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:addMemberVC animated:YES];
            }
            else
            {
                [PromptInfoView showMessage:NSLocalizedString(@"noPowerToAdd", nil)];
                
            }
            
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        
    };
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
